package com.maodou.android.viewmodel.detail

import com.maodou.core.base.BaseViewModel
import com.maodou.core.base.DataUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

/**
 * 详情页数据模型
 */
data class DetailData(
    val id: Int,
    val title: String,
    val content: String,
    val author: String,
    val createTime: String
)

/**
 * 详情页 UI 状态
 */
typealias DetailUiState = DataUiState<DetailData>

/**
 * 详情页 UI 事件
 */
sealed interface DetailUiEvent {
    data class ShowMessage(val message: String) : DetailUiEvent
    object NavigateBack : DetailUiEvent
    data class ShareContent(val content: String) : DetailUiEvent
}

/**
 * 详情页 ViewModel
 * 演示如何使用 BaseViewModel 和通用状态类型
 */
@HiltViewModel
class DetailViewModel @Inject constructor(
    // 这里可以注入 Repository 等依赖
) : BaseViewModel<DetailUiState, DetailUiEvent>() {
    
    override fun createInitialState(): DetailUiState {
        return DetailUiState()
    }
    
    /**
     * 加载详情数据
     */
    fun loadDetail(id: Int, title: String) {
        updateUiState { it.copy(isLoading = true, error = null) }
        
        // 模拟网络请求
        // 实际项目中这里会调用 Repository
        try {
            val detailData = DetailData(
                id = id,
                title = title,
                content = "这是 ID 为 $id 的详情内容，标题是：$title",
                author = "作者姓名",
                createTime = "2024-01-01 12:00:00"
            )
            
            updateUiState {
                it.copy(
                    data = detailData,
                    isLoading = false,
                    error = null
                )
            }
        } catch (e: Exception) {
            updateUiState {
                it.copy(
                    isLoading = false,
                    error = "加载失败: ${e.message}"
                )
            }
        }
    }
    
    /**
     * 分享内容
     */
    fun shareContent() {
        val data = getCurrentUiState().data
        if (data != null) {
            emitUiEvent(DetailUiEvent.ShareContent("${data.title}\n${data.content}"))
        } else {
            emitUiEvent(DetailUiEvent.ShowMessage("没有可分享的内容"))
        }
    }
    
    /**
     * 返回上一页
     */
    fun navigateBack() {
        emitUiEvent(DetailUiEvent.NavigateBack)
    }
    
    /**
     * 重新加载
     */
    fun retry() {
        val currentData = getCurrentUiState().data
        if (currentData != null) {
            loadDetail(currentData.id, currentData.title)
        }
    }
}